<template>
  <div :class="['!w-[var(--left-tree-max-width)] px-0px tree-min-width']">
    <div class="justify-center items-center pl-20px mt-20px">
      <div class="flex-1 mb-15px f-s16 font-bold">工程名称</div>
      <el-select
        v-model="currentDepartment"
        clearable
        placeholder="请选择工程名称"
        @change="handleProductChange"
        style="width: 100%"
      >
        <el-option
          v-for="item in departmentOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </div>
    <ElDivider />
    <div class="items-center pl-20px mt-20px">
      <div class="flex-1 mb-15px f-s16 font-bold">型号设备树</div>
      <ElInput
        v-model="currentchlDepartment"
        class="flex-[2]"
        placeholder="搜索设备型号"
      />
    </div>
    <div class="h-[calc(100%-240px)] overflow-y pl-15px mt-15px">
      <ElTree
        ref="treeEl"
        :data="departmentList"
        default-expand-all
        :show-checkbox="showCheckbox"
        :expand-on-click-node="false"
        node-key="deviceCode"
        :current-node-key="currentNodeKey"
        :props="{
          label: 'deviceShowName',
          children: 'children',
          class: customNodeClass,
        }"
        :filter-node-method="filterNode"
        @current-change="handleCurrentChange"
      >
        <template #default="{ data }">
          <div
            :title="data.deviceShowName"
            class="whitespace-nowrap overflow-ellipsis overflow-hidden"
          >
            {{ data.deviceShowName }}
          </div>
        </template>
      </ElTree>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, defineProps, defineEmits, nextTick } from "vue";
import { ElTree, ElInput, ElDivider } from "element-plus";
import type { DepartmentItem } from "@/components/DepartmentTree/types";
import { useDeviceTreeStore } from "@/store/modules/deviceTreeStore";

// 定义Props
const props = defineProps({
  // 可以添加需要的props
  showCheckbox: {
    type: Boolean,
    default: false,
  },
});

// 定义Emits
const emit = defineEmits(["current-change", "department-change"]);

// 使用Pinia store
const deviceTreeStore = useDeviceTreeStore();

const currentchlDepartment = ref(""); // 搜索关键词
const departmentOptions = ref<{ label: string; value: string }[]>([]);
const currentDepartment = ref(deviceTreeStore.currentDepartment);
const currentNodeKey = ref(deviceTreeStore.currentNodeKey);
const treeEl = ref<InstanceType<typeof ElTree>>();
const departmentList = ref<DepartmentItem[]>([]);

// 修改自定义节点类，只对当前选中节点应用样式
const customNodeClass = (data: DepartmentItem, node: any) => {
  return node.isCurrent ? "is-current-node" : "";
};

// 获取根节点
const getRootDepartment = async () => {
  try {
    const res = await "/dDeviceCatalog/rootList".get();
    // console.log("根节点响应:", res);
    // console.log("根节点数据:", res.data);

    departmentOptions.value = res.data.map((item) => ({
      label: item.deviceName,
      value: item.deviceCode,
    }));



// selectFirstNode();



    // 如果store中有保存的根节点，使用它，否则使用第一个选项
    if (
      deviceTreeStore.currentDepartment &&
      departmentOptions.value.some(
        (opt) => opt.value === deviceTreeStore.currentDepartment
      )
    ) {
      currentDepartment.value = deviceTreeStore.currentDepartment;
    } else if (departmentOptions.value.length > 0) {
      currentDepartment.value = departmentOptions.value[0].value;
      deviceTreeStore.setCurrentDepartment(currentDepartment.value);
    } else {
      currentDepartment.value = "";
      deviceTreeStore.setCurrentDepartment("");
    }

    if (currentDepartment.value) {
      await getTree(currentDepartment.value);
    }
  } catch (error) {
    console.error("获取根节点失败:", error);
  }
};

// 获取树
const getTree = async (rootCode: string) => {
  try {
    // console.log("请求参数:", { parentCode: rootCode });
    const res = await "/dDeviceCatalog/tree".get({ parentCode: rootCode });

    departmentList.value = [res.data] || [];
  // 检查树数据是否为空
    if (departmentList.value && departmentList.value.length === 0) {
      departmentList.value = [res.data] || [];

    // 新增：将设备树数据设置到 Store 中
    deviceTreeStore.setDepartmentList(departmentList.value);
      clearSelection();
      // 清空当前选中节点
      currentNodeKey.value = "";
      deviceTreeStore.setCurrentNode(null);
      // 触发空节点事件
      emit("current-change", null);
      return;
    }

    // else {
    //    // 选中第一个节点
    //   selectFirstNode();
    // }




    // 等待DOM更新
    await nextTick();


    // 树加载完成后，尝试恢复选中的节点或选中第一个节点
    if (deviceTreeStore.currentNodeKey) {
      // 如果store中有保存的选中节点，恢复它
      treeEl.value?.setCurrentKey(deviceTreeStore.currentNodeKey);
    } else {
      // 选中第一个节点
      selectFirstNode();
    }
  } catch (error) {
    console.error("获取树数据失败:", error);
    departmentList.value = [];
    deviceTreeStore.setDepartmentList([]); // 清空 Store 中的树数据
    // 清空选中状态
    currentNodeKey.value = "";
    deviceTreeStore.setCurrentNode(null);
    emit("current-change", null);
  }
};
// 添加清空选中状态的方法
const clearSelection = () => {
  currentNodeKey.value = "";
  treeEl.value?.setCurrentKey(null);
  deviceTreeStore.setCurrentNode(null);
  emit("current-change", null);
};
// 在树组件的 methods 中暴露一个新方法
const selectFirstNode = () => {
  if (departmentList.value.length > 0) {
    const firstNode = findFirstNode(departmentList.value[0]);
    if (firstNode) {
      // 设置当前节点key
      currentNodeKey.value = firstNode.deviceCode;
      // 设置树选中
      treeEl.value?.setCurrentKey(firstNode.deviceCode);
      // 触发current-change事件，确保表单数据更新
      handleCurrentChange(firstNode);
    }
  }
};

// 辅助函数：查找树中的第一个节点
const findFirstNode = (node: DepartmentItem): DepartmentItem => {
  if (!node) return null;
  // 返回当前节点
  return node;
};

// 产品切换
const handleProductChange = async (value: string) => {
  console.log(value, "产品切换");
  currentDepartment.value = value;
  deviceTreeStore.setCurrentDepartment(value);
  // 清空当前选中节点
  deviceTreeStore.setCurrentNode(null);
  currentNodeKey.value = "";
  currentchlDepartment.value = "";
  await getTree(value);
  emit("department-change", value);
};

const filterNode = (value: string, data: DepartmentItem) => {
  if (!value) return true;
  return data.deviceName.includes(value);
};

// 当前节点变化
const handleCurrentChange = (data: DepartmentItem) => {


  if (data) {
    // 保存到store
    deviceTreeStore.setCurrentNode(data);
    currentNodeKey.value = data.deviceCode;

    // 触发事件
    emit("current-change", data);
  }
};

// 监听搜索关键词变化
watch(
  () => currentchlDepartment.value,
  (val) => {
    treeEl.value!.filter(val);
  }
);

// 在 defineExpose 中暴露这个方法
defineExpose({
  refreshTree: async () => {
    if (currentDepartment.value) {
      await getTree(currentDepartment.value);
    }
  },
  refreshRootTree: () => {
    getRootDepartment();
  },
  setCurrentKey: (key: string) => treeEl.value?.setCurrentKey(key),
  getTreeData: () => departmentList.value,
  selectFirstNode, // 添加这个方法
});

onMounted(() => {
  getRootDepartment();
});
</script>

<style scoped lang="less">
.tree-min-width {
  min-width: 200px !important;
}

:deep(.el-tree-node__content) {
  height: 40px !important;
}

:deep(.is-current-node .el-tree-node .el-tree-node__content) {
  background-color: transparent !important;
  color: inherit !important;
  font-weight: normal;
}
:deep(.is-current-node > .el-tree-node__content) {
  background-color: var(--el-color-primary) !important;
  border-radius: 0 20px 20px 0;
  color: var(--el-tree-content-color) !important;
  font-weight: bold;
}

:deep(.el-tree) {
  background: transparent !important;
}

:deep(.el-card) {
  --el-card-bg-color: transparent !important;
  background-color: transparent !important;
}
</style>
